﻿using System;
using System.Linq;

namespace PropertyExpression.ControllableQuery
{
    public interface IParam
    {
        string Name { set; }

        string ToSql();        
    }
    public interface IParam<in T> : IParam
    {
        Func<T> ValueFunc { set; }

        T Value { set; }
    }

    public static class ParamExtensions
    {
        public static string ToSql(this IParam it, string name)
        {
            it.Name = name;
            return it.ToSql();
        }

        public static object Name<T>(this T it)
        {
            var nameHandler = Cache<T>.NameHandler;
            return nameHandler.NameSetter(it, nameHandler.Name);
        }
    }

    internal class Cache<T>
    {
        public static readonly NameHandler<T> NameHandler;
        static Cache()
        {
            var propertyInfo = typeof (T).GetProperties().Single();
            NameHandler = new NameHandler<T>("@" + propertyInfo.Name, DynamicMaterializer.Qwe2<T>(propertyInfo));
        }
    }

    internal class NameHandler<T>
    {
        public readonly string Name;
        public readonly Func<T, string, object> NameSetter;

        public NameHandler(string name, Func<T, string, object> nameSetter)
        {
            Name = name;
            NameSetter = nameSetter;
        }
    }
}